using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;

namespace GameOverlayWPF
{
    public class MapPassword
    {
        public int MapId { get; set; }
        public string MapName { get; set; } = string.Empty;
        public string Password { get; set; } = string.Empty;
    }

    public class MapPasswordResponse
    {
        public bool Success { get; set; }
        public MapPasswordData? Data { get; set; }
        public string? Message { get; set; }
    }

    public class MapPasswordData
    {
        public List<MapPassword> Maps { get; set; } = new List<MapPassword>();
        public string UpdateTime { get; set; } = string.Empty;
    }

    public class MapPasswordService
    {
        private static MapPasswordService? _instance;
        private static readonly object _lock = new object();
        private readonly HttpClient _httpClient;
        private readonly string _apiUrl = "http://113.45.182.203:3000/api/game/map-password/cached";
        
        // 缓存数据
        private MapPasswordData? _cachedData;
        private DateTime _cacheTime = DateTime.MinValue;
        private readonly TimeSpan _cacheExpiry = TimeSpan.FromHours(1); // 缓存1小时

        public static MapPasswordService Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            _instance = new MapPasswordService();
                        }
                    }
                }
                return _instance;
            }
        }

        private MapPasswordService()
        {
            _httpClient = new HttpClient();
            _httpClient.Timeout = TimeSpan.FromSeconds(10);
        }

        public async Task<MapPasswordData?> GetMapPasswordsAsync(bool forceRefresh = false)
        {
            try
            {
                // 检查缓存是否有效
                if (!forceRefresh && _cachedData != null && DateTime.Now - _cacheTime < _cacheExpiry)
                {
                    System.Diagnostics.Debug.WriteLine("使用缓存的地图密码数据");
                    return _cachedData;
                }

                System.Diagnostics.Debug.WriteLine($"从API获取地图密码数据: {_apiUrl}");
                
                using (var response = await _httpClient.GetAsync(_apiUrl))
                {
                    response.EnsureSuccessStatusCode();
                    var responseContent = await response.Content.ReadAsStringAsync();
                    
                    System.Diagnostics.Debug.WriteLine($"API响应: {responseContent}");
                    
                    var options = new JsonSerializerOptions
                    {
                        PropertyNameCaseInsensitive = true
                    };
                    
                    var result = JsonSerializer.Deserialize<MapPasswordResponse>(responseContent, options);
                    
                    if (result != null && result.Success && result.Data != null)
                    {
                        // 更新缓存
                        _cachedData = result.Data;
                        _cacheTime = DateTime.Now;
                        System.Diagnostics.Debug.WriteLine($"地图密码数据已缓存，更新时间: {result.Data.UpdateTime}，地图数量: {result.Data.Maps?.Count ?? 0}");
                        return _cachedData;
                    }
                    else
                    {
                        System.Diagnostics.Debug.WriteLine($"获取地图密码失败: {result?.Message ?? "未知错误"}");
                        // 如果API失败但缓存存在，返回缓存数据
                        if (_cachedData != null)
                        {
                            System.Diagnostics.Debug.WriteLine("API失败，使用旧缓存数据");
                            return _cachedData;
                        }
                        return null;
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                System.Diagnostics.Debug.WriteLine($"HTTP请求错误: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                // 如果出错但缓存存在，返回缓存数据
                if (_cachedData != null)
                {
                    System.Diagnostics.Debug.WriteLine("HTTP请求出错，使用缓存数据");
                    return _cachedData;
                }
                return null;
            }
            catch (TaskCanceledException ex)
            {
                System.Diagnostics.Debug.WriteLine($"请求超时: {ex.Message}");
                // 如果出错但缓存存在，返回缓存数据
                if (_cachedData != null)
                {
                    System.Diagnostics.Debug.WriteLine("请求超时，使用缓存数据");
                    return _cachedData;
                }
                return null;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取地图密码时出错: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"错误类型: {ex.GetType().Name}");
                System.Diagnostics.Debug.WriteLine($"堆栈跟踪: {ex.StackTrace}");
                // 如果出错但缓存存在，返回缓存数据
                if (_cachedData != null)
                {
                    System.Diagnostics.Debug.WriteLine("请求出错，使用缓存数据");
                    return _cachedData;
                }
                return null;
            }
        }

        public void ClearCache()
        {
            _cachedData = null;
            _cacheTime = DateTime.MinValue;
        }
    }
}

